package com.xinsoft.controller.basic;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xinsoft.aop.ano.SysLog;
import com.xinsoft.common.BusinessType;
import com.xinsoft.common.Response;
import com.xinsoft.constant.Const;
import com.xinsoft.entity.dto.SysApproveFlowNodeDto;
import com.xinsoft.entity.dto.SysFlowParam;
import com.xinsoft.entity.po.SysAction;
import com.xinsoft.entity.po.SysApproveFlowNode;
import com.xinsoft.entity.po.SysApproveNodeRel;
import com.xinsoft.entity.po.SysUser;
import com.xinsoft.service.SysActionService;
import com.xinsoft.service.SysApproveFlowNodeService;
import com.xinsoft.service.SysApproveNodeRelService;
import com.xinsoft.service.SysUserService;
import com.xinsoft.validator.ValidatorUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName SysNodeController
 * @Description 流程节点管理
 * @Author lijie
 * @Date 2023/5/22 13:50 星期一
 * @Version 1.0
 */
@RestController
@RequestMapping("/system/node")
@Api(value = "SysNodeController", tags = {"流程节点管理控制层"})
public class SysNodeController {

    @Autowired
    private SysApproveFlowNodeService nodeService;

    @Autowired
    private SysApproveNodeRelService relService;

    @Autowired
    SysUserService userService;

    @Autowired
    SysActionService actionService;

    /**
     * @return com.xinsoft.common.Response<?>
     * @Author Li9527
     * @Description 节点管理-新增
     * @Date 2023/5/17 9:57
     * @params dept
     **/
    @SysLog(title = "节点管理-新增", businessType = BusinessType.INSERT)
    @ApiOperation("新增")
    @PostMapping("/add")
    public Response<?> add(@RequestBody SysApproveFlowNodeDto node) {
        // 参数校验
        ValidatorUtils.validateEntity(node);
        SysApproveFlowNode flowNode = nodeService.getOne(new QueryWrapper<SysApproveFlowNode>()
                .eq("flow_id",node.getFlowId())
                .eq("node_name", node.getNodeName()));
        if (flowNode != null) {
            return Response.fail("该流程下已存在该节点,请不要重复添加");
        }
        nodeService.add(node,node.getNum());
        SysAction sysAction = new SysAction();
        sysAction.setActionName(node.getNodeName());
        sysAction.setActionStatus(Const.AUDIT_STATUS_NORMAL);
        sysAction.setActionDescription(node.getDescription());
        sysAction.setNodeId(node.getId());
        actionService.save(sysAction);
        return Response.succeed();
    }

    /**
     * @return com.xinsoft.common.Response<?>
     * @Author Li9527
     * @Description 更新
     * @Date 2023/5/17 9:57
     * @params dept
     **/
    @ApiOperation("更新")
    @SysLog(title = "节点管理-编辑", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public Response<?> edit(@RequestBody SysApproveFlowNodeDto node) {
        // 参数校验
        ValidatorUtils.validateEntity(node);
        SysApproveFlowNode flowNode = nodeService.getOne(new QueryWrapper<SysApproveFlowNode>()
                .eq("flow_id",node.getFlowId())
                .eq("node_name", node.getNodeName()));
        if (flowNode != null && !node.getId().equals(flowNode.getId())) {
            return Response.fail("该流程下已存在该节点或节点排序一致,请不要重复添加");
        }
        nodeService.updateById(node);
        // 更新完节点自动更新节点对应动作名称，动作描述
        List<SysAction> sysActionList = actionService.list(new QueryWrapper<SysAction>().eq("node_id",node.getId()));
        if(sysActionList.size()> 0){
            for (int i = 0; i < sysActionList.size(); i++) {
                sysActionList.get(i).setActionName(node.getNodeName());
                sysActionList.get(i).setActionDescription(node.getDescription());
            }
            actionService.updateBatchById(sysActionList);
        }
        if(node.getResourceId().length > 0){
            relService.remove(new QueryWrapper<SysApproveNodeRel>().eq("node_id",node.getId()));
            List<SysApproveNodeRel> relList = new ArrayList<>();
            for (int i = 0; i < node.getResourceId().length; i++) {
                SysApproveNodeRel rel = new SysApproveNodeRel();
                rel.setNodeId(node.getId());
                rel.setResourceId(node.getResourceId()[i]);
                relList.add(rel);
            }
            relService.saveBatch(relList);
        }
        return Response.succeed();
    }

    /**
     * @return com.xinsoft.common.Response<?>
     * @Author Li9527
     * @Description 获取详情
     * @Date 2023/5/17 9:57
     * @params id
     **/
    @ApiOperation("获取详情")
    @GetMapping("/detail")
    public Response<?> detail(@RequestParam(value = "id", defaultValue = "", required = true) Integer id) {
        SysApproveFlowNodeDto node = nodeService.getInfoById(id);
        // 封装用户名
        if (node.getFlowType() == 1) {
            List<SysApproveNodeRel> listRel = relService.list(new QueryWrapper<SysApproveNodeRel>().eq("node_id", node.getId()));
            if( listRel.size() > 0){
//                Map<Integer,String> map = new HashMap<>();
                List<Integer> reIdList = new ArrayList<>();
                for (int j = 0; j < listRel.size(); j++) {
                    reIdList.add(listRel.get(j).getResourceId());
                }
                List<SysUser> sysUserList = userService.listByIds(reIdList);
                List<String> userNameList = new ArrayList<>();
                if (sysUserList.size() > 0) {
                    for (int j = 0; j < sysUserList.size(); j++) {
//                        map.put(sysUserList.get(j).getId(),sysUserList.get(j).getRealName());
                        userNameList.add(sysUserList.get(j).getRealName());
                    }
                }
                node.setUserNameList(userNameList);
//                node.setResourceMap(map);
            }
        }

        return Response.succeed(node);
    }

    /**
     * @return com.xinsoft.common.Response<?>
     * @Author Li9527
     * @Description 删除
     * @Date 2023/5/12 9:20
     * @params ids
     **/
    @ApiOperation("删除")
    @SysLog(title = "节点管理-删除", businessType = BusinessType.DELETE)
    @PostMapping("/del")
    public Response<?> del(@RequestBody List<Integer> ids) {
        if(ids.size() > 1){
            return Response.fail("流程节点只支持单个删除,请修正");
        }
        nodeService.deleteNode(ids.get(0));
        // 同步删除通知动作表
        actionService.remove(new QueryWrapper<SysAction>().eq("node_id",ids.get(0)));
        return Response.succeed();
    }

    /**
     * @return com.xinsoft.common.Response<?>
     * @Author Li9527
     * @Description 节点管理分页
     * @Date 2023/5/18 10:51
     * @params param
     **/
    @PostMapping("/pageList")
    public Response<?> pageList(@Valid @RequestBody SysFlowParam param) {
        if(param.getFlowId() == null){
            return Response.fail("流程id必传");
        }
        return Response.succeed(nodeService.findPageListByParam(param));
    }


}
